<template>
  <div>
    <!-- 表格部分 -->
    <el-card style="margin-top: 10px">
      <div style="margin-bottom: 5px">
        <el-button
          type="danger"
          plain
          size="small"
          :disabled="multiple"
          @click="onDelete"
          ><el-icon><DeleteFilled /></el-icon>删除</el-button
        >
        <el-button plain size="small" type="primary" @click="onAdd"
          ><el-icon><DeleteFilled /></el-icon>添加</el-button
        >
      </div>
      <el-table
        :data="tableData"
        style="width: 100%"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="50" />
        <el-table-column prop="name" label="角色" />
        <el-table-column prop="priority" label="排列顺序" />
        <el-table-column label="操作选项">
          <template #default="{ row }">
            <el-button
              link
              plain
              type="primary"
              size="small"
              @click="onEdit(row)"
              ><el-icon><Edit /></el-icon>修改</el-button
            >
            <el-button
              link
              plain
              type="primary"
              size="small"
              @click="onRevocation(row)"
              ><el-icon><Delete /></el-icon>删除</el-button
            >
            <el-button
              link
              plain
              type="primary"
              size="small"
              @click="onMemberManage(row.id)"
              ><el-icon><Setting /></el-icon>成员管理</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页器 -->
      <pagination
        v-show="total > 0"
        :total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="getList"
      />
    </el-card>
    <el-dialog
      v-model="addDialogVisible"
      :title="title"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      @close="onReset(addRuleFormRef)"
      width="45%"
    >
      <el-form
        ref="addRuleFormRef"
        style="min-width: 500px"
        :model="addRuleForm"
        :rules="addRules"
        label-width="120"
        class="demo-ruleForm"
        status-icon
      >
        <el-row>
          <el-col :span="12">
            <el-form-item label="角色名" prop="name" name="name" required>
              <el-input
                v-model="addRuleForm.name"
                placeholder="请输入角色名"
                clearable
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="排列顺序" prop="priority" name="priority">
              <el-input
                v-model="addRuleForm.priority"
                placeholder="请输入排列顺序"
                clearable
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="拥有所有权限">
              <el-checkbox v-model="addRuleForm.super" @change="onSuper"
                >是</el-checkbox
              >
              <!-- <el-radio-group v-model="addRuleForm.super" @change="onSuper">
                <el-radio value="1">是</el-radio>
                <el-radio value="0">否</el-radio>
              </el-radio-group> -->
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="功能权限">
              <el-checkbox
                v-model="menuExpand"
                @change="handleCheckedTreeExpand($event, 'menu')"
                >展开/折叠</el-checkbox
              >
              <el-checkbox
                v-model="menuNodeAll"
                :disabled="isSuper"
                @change="handleCheckedTreeNodeAll($event, 'menu')"
                >全选/全不选</el-checkbox
              >
              <el-checkbox
                v-model="addRuleForm.menuCheckStrictly"
                @change="handleCheckedTreeConnect($event, 'menu')"
                >父子联动</el-checkbox
              >
              <el-tree
                class="tree-border"
                :data="menuOptions"
                show-checkbox
                ref="menuRef"
                @check="handleNodeClick"
                node-key="id"
                :check-strictly="!addRuleForm.menuCheckStrictly"
                empty-text="加载中，请稍候"
                :props="defaultProps"
              ></el-tree>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="onReset(addRuleFormRef)">重 置</el-button>
          <el-button type="primary" @click="onSubmit(addRuleFormRef)"
            >提 交</el-button
          >
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script  setup>
import { ref, reactive, nextTick } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useRouter } from 'vue-router'
import {
  getRoleList,
  getupdate,
  updateRole,
  createRoleList,
  deleteRole,
  createRole
} from '@/api/user/role.js'
const router = useRouter()

const ids = ref([])
const multiple = ref(true)
const addRuleFormRef = ref()
const addDialogVisible = ref(false)
const total = ref(0)
const title = ref('')
const menuOptions = ref([])
const menuRef = ref(null)
const menuNodeAll = ref(false)
const menuExpand = ref(false)
const updateId = ref('')
const isSuper = ref(false)
const defaultProps = ref({
  children: 'children',
  label: 'name',
  disabled: () => {
    return false
  }
})

// 添加表单的内容
const addRuleForm = ref({
  name: '',
  priority: '',
  super: '',
  menuCheckStrictly: true
})

const tableData = ref([])

// 校验规则
const addRules = reactive({
  name: [{ required: true, message: '请输入角色名', trigger: 'blur' }],
  priority: [{ required: true, message: '请输入排列顺序', trigger: 'blur' }]
})

const queryParams = ref({
  pageNo: 1,
  pageSize: 10
})

const getList = () => {
  getRoleList(queryParams.value).then((res) => {
    tableData.value = res.data.list
    total.value = res.data.list.length
  })
}
// 选择是否拥有全部权限
const onSuper = (value) => {
  // addRuleForm.value.menuCheckStrictly = true
  if (value) {
    isSuper.value = true
    handleCheckedTreeConnect(true, 'menu')
    menuNodeAll.value = true
    nextTick(() => {
      menuRef.value.setCheckedNodes(isSuper.value ? menuOptions.value : [])
      defaultProps.value.disabled = () => {
        return true
      }
    })
  } else {
    isSuper.value = false
    menuRef.value.setCheckedNodes(isSuper.value ? menuOptions.value : [])
    defaultProps.value.disabled = () => {
      return false
    }
  }
}

// 点击修改按钮
const onEdit = (row) => {
  title.value = '修改'
  addDialogVisible.value = true
  updateId.value = row.id
  getupdate({ id: row.id }).then((res) => {
    addRuleForm.value.name = res.data.cmsRole.name
    addRuleForm.value.priority = res.data.cmsRole.priority
    addRuleForm.value.super = res.data.cmsRole.super
    const data = res.data.cmsPermissionRoles.map((item) => item.permissionId)
    menuRef.value.setCheckedKeys(data, false)
    // data.forEach((v) => {
    //   nextTick(() => {
    //     console.log(menuRef.value.setChecked)
    //     menuRef.value.setChecked(v, true, true)
    //   })
    // })
    menuOptions.value = res.data.cmsPermissionList
    if (res.data.cmsRole.super) {
      menuNodeAll.value = true
      // addRuleForm.value.menuCheckStrictly = false
      defaultProps.value.disabled = () => {
        return true
      }
      isSuper.value = true
      // menuRef.value.setCheckedNodes(value ? menuOptions.value : [])
    } else {
      defaultProps.value.disabled = () => {
        return false
      }
      isSuper.value = false
      menuNodeAll.value = false
    }
  })
}
const onAdd = () => {
  title.value = '添加'
  addDialogVisible.value = true
  addRuleForm.value = {
    name: '',
    priority: '',
    super: ''
  }
  isSuper.value = false
  menuNodeAll.value = true
  if (menuRef.value) {
    menuRef.value.setCheckedKeys([], false)
  }

  defaultProps.value.disabled = () => {
    return false
  }
  createRoleList().then((res) => {
    menuOptions.value = res.data.list
  })
}
// 批量删除
const onDelete = () => {
  deleteRole({ roleId: ids.value }).then((res) => {
    if (res.success) {
      getList()
      ElMessage({
        type: 'success',
        message: res.message
      })
    }
  })
}
// 删除
const onRevocation = (row) => {
  ElMessageBox.confirm('您确定要删除这条数据吗？', '系统提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  })
    .then(() => {
      deleteRole({ roleId: [row.id] }).then((res) => {
        if (res.success) {
          getList()
          ElMessage({
            type: 'success',
            message: res.message
          })
        }
      })
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '取消删除'
      })
    })
}
// 选择权限的key值
const handleNodeClick = (checkedKeys, selectkeys) => {
  console.log(selectkeys.checkedKeys)
}
// 提交
const onSubmit = async (formEl) => {
  if (!formEl) return
  await formEl.validate((valid, fields) => {
    if (valid) {
      addDialogVisible.value = false
      const params = {
        name: addRuleForm.value.name,
        priority: addRuleForm.value.priority,
        is_super: addRuleForm.value.super,
        permIds: menuRef.value.getCheckedKeys()
      }
      if (title.value === '添加') {
        // 调接口
        createRole(params).then((res) => {
          if (res.success) {
            getList()
            ElMessage({
              type: 'success',
              message: res.message
            })
          }
        })
      } else {
        params.id = updateId.value
        updateRole(params).then((res) => {
          if (res.success) {
            getList()
            ElMessage({
              type: 'success',
              message: res.message
            })
          }
        })
      }
    } else {
      console.log('error submit!', fields)
    }
  })
}
// 重置
const onReset = (formEl) => {
  if (title.value === '添加') {
    addRuleForm.value = {
      name: '',
      priority: '',
      super: ''
    }
    menuRef.value.setChecked = []
  } else {
    getupdate({ id: updateId.value }).then((res) => {
      addRuleForm.value.name = res.data.cmsRole.name
      addRuleForm.value.priority = res.data.cmsRole.priority
      addRuleForm.value.super = res.data.cmsRole.super
      if (res.data.cmsRole.super) {
        menuNodeAll.value = true
        addRuleForm.value.menuCheckStrictly = false
      }
    })
  }
  formEl.resetFields()
}

// 成员管理
const onMemberManage = (roleId) => {
  router.push({
    path: 'MemberManagement',
    query: {
      roleId: roleId
    }
  })
}

/** 树权限（展开/折叠） */
const handleCheckedTreeExpand = (value, type) => {
  if (type === 'menu') {
    const treeList = menuOptions.value
    for (let i = 0; i < treeList.length; i++) {
      menuRef.value.store.nodesMap[treeList[i].id].expanded = value
    }
  }
}

/** 树权限（全选/全不选） */
const handleCheckedTreeNodeAll = (value, type) => {
  if (type === 'menu') {
    menuRef.value.setCheckedNodes(value ? menuOptions.value : [])
  }
}

/** 树权限（父子联动） */
const handleCheckedTreeConnect = (value, type) => {
  if (type === 'menu') {
    addRuleForm.value.menuCheckStrictly = !!value
  }
}

const handleSelectionChange = (selection) => {
  ids.value = selection.map((item) => item.id)
  multiple.value = !selection.length
}
getList()
</script>

<style lang="scss" scoped>
::v-deep {
  .el-table {
    .el-table__header-wrapper {
      th {
        word-break: break-word;
        background-color: #f8f8f9 !important;
        color: #515a6e;
        height: 40px !important;
        font-size: 13px;
      }
    }
  }
}
::v-deep {
  .el-form {
    .el-form-item {
      .el-form-item__label {
        font-weight: bold !important;
      }
    }
  }
}

::v-deep {
  .el-form {
    .el-form-item .second_label {
      .el-form-item__label {
        font-weight: normal !important;
        margin-top: 10px;
      }
    }
  }
}
::v-deep {
  .second_label {
    .el-form-item__error {
      position: static !important;
    }
  }
}

::v-deep {
  .tree-border {
    margin-top: 5px;
    border: 1px solid #e5e6e7;
    background: #fff none;
    border-radius: 4px;
    width: 100%;
  }
}
</style>
